﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Lonewolf.Infrastructure
{
    /// <summary>
    /// Select2树形下拉列表模型。
    /// </summary>
    public class TreeSelect
    {
        public string id { get; set; }
        public string text { get; set; }
        public int? level { get; set; }
        public string parentId { get; set; }
        public object data { get; set; }
    }

    public static class TreeSelectHelper
    {
        public static string ToTreeSelectJson(this List<TreeSelect> data)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            sb.Append(ToTreeSelectJson(data,"", 0, ""));
            sb.Append("]");
            return sb.ToString();
        }
        public static string ToTypeSelectJson(this List<TreeSelect> data)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            foreach (TreeSelect entity in data)
            {
                string strJson = JsonConvert.SerializeObject(entity);
                sb.Append(strJson);
            }
            sb.Append("]");
            return sb.ToString().Replace("}{", "},{"); ;
        }
        private static string ToTreeSelectJson(List<TreeSelect> data, string parentId, int level, string blank)
        {
            StringBuilder sb = new StringBuilder();
            List<TreeSelect> childList;
            if (level==0)
            {
                var lepar = data.Find(a => a.level == 0);
                childList = data.FindAll(t => t.parentId == lepar.parentId);
            }
            else
            {
                childList = data.FindAll(t => t.parentId == parentId);
            }
            var tabline = "";
            if (level != 0)
            {
                //tabline＝"  ";
                tabline = "　";
            }
            if (childList.Count > 0)
            {
                tabline = tabline + blank;
            }
            foreach (TreeSelect entity in childList)
            {
                entity.text = tabline + entity.text;
                string strJson = JsonConvert.SerializeObject(entity);
                sb.Append(strJson);
                sb.Append(ToTreeSelectJson(data, entity.id, 1, tabline));
            }
            return sb.ToString().Replace("}{", "},{");
        }
    }
}
